package org.glickr.api.places

import org.glickr.api.FlickrApiMethod
import groovy.util.slurpersupport.GPathResult
import org.glickr.FlickrServicePluginException
import org.glickr.FlickrServiceApiException
import org.glickr.FlickrPlaceType
import org.glickr.FlickrPlace

/* ----------------------------------------------------------------------------------------------------
REQUEST: flickr.places.getPlaceTypes
INFO: Fetches a list of available place types for Flickr.

AUTHENTICATION: This method does not require authentication.

ARGUMENTS:
api_key (Required): Your API application key.

EXAMPLE RESPONSE:
<place_types>
  <place_type place_type_id="22">neighbourhood</place_type>
  <place_type place_type_id="7">locality</place_type>
  <place_type place_type_id="9">county</place_type>
  <place_type place_type_id="8">region</place_type>
  <place_type place_type_id="12">country</place_type>
  <place_type place_type_id="29">continent</place_type>
</place_types>
---------------------------------------------------------------------------------------------------- */

class placesGetPlaceTypes implements FlickrApiMethod {
    //
    //  API METHOD
    //
    static final String apiMethod = 'flickr.places.getPlaceTypes'

    //
    //  VALIDATOR
    //
    def validatorClosure = { Object dummy ->
        return [validated:true]
    }

    //
    //  PARAMS
    //
    def paramsClosure = { Object dummy ->
       [:]
    }

    //
    //  PROCESSOR
    //
    Closure processorClosure = { GPathResult response, Object dummy ->
        ArrayList<FlickrPlaceType> placeTypes = []
        response.place_types.children().findAll{ it.name() == 'place_type' }.each {
            FlickrPlaceType placeType = new FlickrPlaceType()
            placeType.id    = it.@id.toInteger()
            placeType.title = it.toString()
            placeTypes.add(placeType)
        }
        return placeTypes
    }

    //
    //  ERROR CODES
    //
    Closure errorsClosure = { GPathResult response ->
        // recoverable errors
        if ([100,105,116].contains(response.err.@code.toInteger())) {
            return new FlickrServiceApiException(response)
        } else {
            return new FlickrServicePluginException(response)
        }
    }
}


//EXAMPLE RESPONSE:
//<place_types>
//  <place_type place_type_id="22">neighbourhood</place_type>
//  <place_type place_type_id="7">locality</place_type>
//  <place_type place_type_id="9">county</place_type>
//  <place_type place_type_id="8">region</place_type>
//  <place_type place_type_id="12">country</place_type>
//  <place_type place_type_id="29">continent</place_type>
//</place_types>

